package cn.rxmind.dlog.common;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.util.function.Predicate;

/**
 *
 * @description 核心切面，拦截配置所规定的接口请求
 *              这里拦截主要是根据预先设置的一些规则把
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2020/7/11 1:57 下午
 */
@Aspect
public final class DLogAspect {

    private Predicate<JoinPoint> needCopyData;

    public DLogAspect(Predicate<JoinPoint> needCopyData) {
        if(needCopyData == null){
            throw new IllegalArgumentException("needCopyData param is null");
        }
        this.needCopyData = needCopyData;
    }


    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.GetMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.PatchMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.PutMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    public final void pointCut(){}


    @Around("pointCut()")
    public final Object aroundPointCut(ProceedingJoinPoint joinPoint) throws Throwable {

        long startTime = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        // 根据joinPoint判断是否需要被拦截
        if(needCopyData.test(joinPoint)){
            // 将拦截后收集到的初步的数据放到线程变量里面
            DLogData dLogData = new DLogData();
            dLogData.setStartTime(startTime);
            dLogData.setEndTime(endTime);
            dLogData.setArgs(joinPoint.getArgs());
            dLogData.setResult(proceed);
            DLogLocalData.setLogData(dLogData);
        }

        return proceed;
    }

}
